package renguanyu.app.codebuilder.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;

import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.DialogPane;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import renguanyu.app.codebuilder.util.DaoFactory;

public class DiyTemplateView extends AnchorPane {

    HBox toolBar = new HBox();
    TextField queryTextField = new TextField();
    Button queryButton = new Button("搜索");
    Button clearButton = new Button("清空");
    Button saveButton = new Button("新增");
    Button deleteButton = new Button("删除");
    Button updateButton = new Button("修改");

    TableView<ObservableMap<String, String>> templateTable = new TableView();
    TableColumn<ObservableMap<String, String>,String> templateIDColumn = new TableColumn("模板ID");
    TableColumn<ObservableMap<String, String>,String> templateNameColumn = new TableColumn("模板名称");

    SaveTemplateHeadView saveTemplateHeadView;
    SaveTemplateBodyView saveTemplateBodyView;

    public DiyTemplateView(CodeBuilderView codeBuilderView){
        initUI();
        initEvent();  
        initData();
    }



    private void initUI() {

        toolBar.setSpacing(10.0);
        AnchorPane.setLeftAnchor(toolBar,10.0);
        AnchorPane.setTopAnchor(toolBar,10.0);

        toolBar.getChildren().addAll(queryTextField,queryButton,clearButton,saveButton,deleteButton,updateButton);

        templateTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        templateTable.setPrefHeight(200.0);
        templateTable.setPrefWidth(200.0);
        AnchorPane.setLeftAnchor(templateTable,10.0);
        AnchorPane.setTopAnchor(templateTable,40.0);
        AnchorPane.setRightAnchor(templateTable,10.0);
        AnchorPane.setBottomAnchor(templateTable,10.0);

        templateIDColumn.setPrefWidth(75.0);
        templateIDColumn.setVisible(false);
        templateIDColumn.setCellValueFactory(new MapValueFactory("TEMP_ID"));
        templateNameColumn.setPrefWidth(75.0);
        templateNameColumn.setCellValueFactory(new MapValueFactory("TEMP_NAME"));
        templateTable.getColumns().addAll(templateIDColumn,templateNameColumn);

        this.getChildren().addAll(toolBar,templateTable);

        this.setPrefHeight(180.0);
        this.setPrefWidth(200.0);
    }

    private void initEvent() {
        queryButton.setOnAction(event -> initData());
        saveButton.setOnAction(event -> saveTemplateTo());
        clearButton.setOnAction(event -> clearQueryField());
        deleteButton.setOnAction(event -> deleteTemplate());
        updateButton.setOnAction(event -> updateTemplateTo());
        templateTable.setOnMouseClicked(event -> {if(event.getClickCount()==2){updateTemplateTo();}});

    }

    private void clearQueryField() {
        queryTextField.clear();
        initData();
    }

    private void deleteTemplate() {
        TableView.TableViewSelectionModel selectionModel = templateTable.getSelectionModel();

        if(!selectionModel.isEmpty()){
            ObservableMap<String, String> selectedItem = (ObservableMap<String, String>) selectionModel.getSelectedItem();
            String tempId = selectedItem.get("TEMP_ID");
            boolean flag = DaoFactory.getTemplateDao().delete(tempId);
            if(flag){
                initData();
            }
            else{
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("消息提示框");
                alert.setHeaderText("失败");
                alert.show();
            }
        }

    }

    private void updateTemplateTo() {
        TableView.TableViewSelectionModel selectionModel = templateTable.getSelectionModel();
        if(!selectionModel.isEmpty()){
            ObservableMap<String, String> template = (ObservableMap<String, String>) selectionModel.getSelectedItem();
            showUpdateTemplateView(template);
        }

    }

    public void showUpdateTemplateView(ObservableMap<String, String> template) {
        String templateId = template.get("TEMP_ID");
//        ObservableMap<String, String> template = DaoFactory.getTemplateDao().queryOne(templateId);
        ObservableList<ObservableMap<String, String>> templateData = DaoFactory.getTemplateDataDao().query(templateId);

        Dialog<ButtonType> saveTemplateDialog = new Dialog<>();
        saveTemplateDialog.setTitle("更新模板");
        DialogPane dialogPane = saveTemplateDialog.getDialogPane();

        saveTemplateBodyView = new SaveTemplateBodyView(template,templateData);
        dialogPane.setContent(saveTemplateBodyView);

        saveTemplateHeadView = new SaveTemplateHeadView(saveTemplateBodyView,template);
        dialogPane.setHeader(saveTemplateHeadView);

        dialogPane.getButtonTypes().addAll(ButtonType.OK,ButtonType.CLOSE);
        saveTemplateDialog.initModality(Modality.WINDOW_MODAL);
        saveTemplateDialog.setResizable(true);
        Optional<ButtonType> optional = saveTemplateDialog.showAndWait();

        if(optional.get()==ButtonType.OK) {

            updateTemplate();
        }
    }

    private void updateTemplate() {

        boolean flag = false;

        List<String> tempDataIdList = new ArrayList<>();
        List<String> fileNameList = new ArrayList<>();
        List<String> fileDataList = new ArrayList<>();

        Set<Node> tempDataIdSet = saveTemplateBodyView.rowList.lookupAll(".tempDataIdTextAreaCss");
        Set<Node> fileNameSet = saveTemplateBodyView.rowList.lookupAll(".fileNameTextFieldCss");
        Set<Node> fileDataSet = saveTemplateBodyView.rowList.lookupAll(".fileDataTextAreaCss");

        tempDataIdSet.forEach(action->{
            Button removeButton = (Button)action;
            String templateId = removeButton.getId();
            tempDataIdList.add(templateId);
        });
        fileNameSet.forEach(action->{
            TextField fileNameTextField = (TextField)action;
            String fileName = fileNameTextField.getText();
            fileNameList.add(fileName);
        });
        fileDataSet.forEach(action->{
            TextArea fileDataTextArea = (TextArea)action;
            String fileData = fileDataTextArea.getText();
            fileDataList.add(fileData);
        });
        String templateName = saveTemplateHeadView.getTemplateTextField().getText();
        String templateId = saveTemplateHeadView.getTemplate().get("TEMP_ID");

        for(int i=0;i<tempDataIdList.size();i++){
            String tempDataId = tempDataIdList.get(i);
            String fileName = fileNameList.get(i);
            String fileData = fileDataList.get(i);
            boolean isUpdate = false;
            boolean isExist = DaoFactory.getTemplateDataDao().isExist(tempDataId);
            if(isExist){
                flag = DaoFactory.getTemplateDataDao().update(tempDataId,fileName,fileData);
            }else{
                flag = DaoFactory.getTemplateDataDao().save(tempDataId,templateId,fileName,fileData);
            }

        }

        flag = DaoFactory.getTemplateDao().update(templateId,templateName);

        if(flag){
            initData();
        }
        else{
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("消息提示框");
            alert.setHeaderText("失败");
            alert.show();
        }

    }

    private void saveTemplateTo() {

        Dialog<ButtonType> saveTemplateDialog = new Dialog<>();
        saveTemplateDialog.setTitle("添加模板");
        DialogPane dialogPane = saveTemplateDialog.getDialogPane();

        saveTemplateBodyView = new SaveTemplateBodyView(null, null);
        dialogPane.setContent(saveTemplateBodyView);


        saveTemplateHeadView = new SaveTemplateHeadView(saveTemplateBodyView, null);
        dialogPane.setHeader(saveTemplateHeadView);

        dialogPane.getButtonTypes().addAll(ButtonType.OK,ButtonType.CLOSE);
        saveTemplateDialog.initModality(Modality.WINDOW_MODAL);
        saveTemplateDialog.setResizable(true);
        Optional<ButtonType> optional = saveTemplateDialog.showAndWait();

        if(optional.get()==ButtonType.OK) {

            saveTemplate();
        }
    }

    private void saveTemplate() {
        boolean flag = false;

        List<String> fileNameList = new ArrayList<>();
        List<String> fileDataList = new ArrayList<>();

        Set<Node> fileNameSet = saveTemplateBodyView.rowList.lookupAll(".fileNameTextFieldCss");
        Set<Node> fileDataSet = saveTemplateBodyView.rowList.lookupAll(".fileDataTextAreaCss");

        fileNameSet.forEach(action->{
            TextField fileNameTextField = (TextField)action;
            String fileName = fileNameTextField.getText();
            fileNameList.add(fileName);
        });
        fileDataSet.forEach(action->{
            TextArea fileDataTextArea = (TextArea)action;
            String fileData = fileDataTextArea.getText();
            fileDataList.add(fileData);
        });

        String templateName = saveTemplateHeadView.templateTextField.getText();
        String templateId = UUID.randomUUID().toString();
        flag = DaoFactory.getTemplateDao().save(templateId,templateName);

        if(flag){
            for (int i = 0; i < fileNameList.size(); i++) {

                String fileName = fileNameList.get(i);
                String fileData = fileDataList.get(i);

                String templateDataId = UUID.randomUUID().toString();
                flag = DaoFactory.getTemplateDataDao().save(templateDataId,templateId,fileName,fileData);


            }
            if(flag){
                initData();
            }
            else{
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("消息提示框");
                alert.setHeaderText("失败");
                alert.show();
            }
        }
    }

    public void initData() {
        String templateName = queryTextField.getText();
        ObservableList<ObservableMap<String, String>> list = DaoFactory.getTemplateDao().query(templateName);
        templateTable.getItems().setAll(list);
    }

}
